/**
 * SSE连接工具类
 */
export class SSEClient {
  constructor() {
    this.eventSource = null
  }

  /**
   * 连接SSE
   * @param {string} url - SSE接口地址
   * @param {Object} callbacks - 回调函数对象
   * @param {Function} callbacks.onMessage - 接收消息回调
   * @param {Function} callbacks.onError - 错误回调
   * @param {Function} callbacks.onOpen - 连接打开回调
   * @param {Function} callbacks.onClose - 连接关闭回调
   */
  connect(url, callbacks = {}) {
    try {
      this.eventSource = new EventSource(url)

      this.eventSource.onopen = (event) => {
        console.log('SSE连接已打开:', event)
        if (callbacks.onOpen) {
          callbacks.onOpen(event)
        }
      }

      this.eventSource.onmessage = (event) => {
        console.log('收到SSE消息:', event.data)
        if (callbacks.onMessage) {
          callbacks.onMessage(event.data)
        }
      }

      this.eventSource.onerror = (event) => {
        console.error('SSE连接错误:', event)

        // 检查连接状态
        if (this.eventSource.readyState === EventSource.CLOSED) {
          console.log('SSE连接已正常关闭')
          if (callbacks.onClose) {
            callbacks.onClose(event)
          }
        } else {
          console.error('SSE连接异常错误')
          if (callbacks.onError) {
            callbacks.onError(event)
          }
        }
      }

    } catch (error) {
      console.error('创建SSE连接失败:', error)
      if (callbacks.onError) {
        callbacks.onError(error)
      }
    }
  }

  /**
   * 关闭SSE连接
   */
  close() {
    if (this.eventSource) {
      this.eventSource.close()
      this.eventSource = null
      console.log('SSE连接已关闭')
    }
  }

  /**
   * 检查连接状态
   */
  isConnected() {
    return this.eventSource && this.eventSource.readyState === EventSource.OPEN
  }
}

/**
 * 创建SSE连接的便捷函数
 * @param {string} url - SSE接口地址
 * @param {Object} callbacks - 回调函数对象
 * @returns {SSEClient} SSE客户端实例
 */
export function createSSEConnection(url, callbacks) {
  const client = new SSEClient()
  client.connect(url, callbacks)
  return client
}
